package com.study.sgu.hsp.tcp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/28 22:09
 */
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {

        //创建两个线程组 bossGrop 和workerGrop
        //只处理连接请求
        EventLoopGroup bossGrop = new NioEventLoopGroup();
        NioEventLoopGroup workerGrop = new NioEventLoopGroup();

        //服务器端的启动对象
        ServerBootstrap bootstrap = new ServerBootstrap();

        try {
            //设置两个线程组
            bootstrap.group(bossGrop, workerGrop)//
                    .channel(NioServerSocketChannel.class)//
                    .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保存活动连接状态
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        //给pipline设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    }); //设置对应的管道处理器

            System.out.println("服务器准备好了 is ready……");

            //绑定一个端口并同步处理，生成一个ChannelFuture
            ChannelFuture cf = bootstrap.bind(6668).sync();

            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        } finally {
            bossGrop.shutdownGracefully();
            workerGrop.shutdownGracefully();
        }
    }

}
